package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的登录密码进行md5加密,然后与数据库中的信息进行对比
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /*@Autowired
    private HttpServletRequest request;//从请求头中获取jwt令牌来获取当前登录用户id,替换成了从当前线程存储空间中获取
    */

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void insert(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();//创建一个实体类对象,交给持久层进行数据处理

        //调用spring中的工具类进行对象的属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);//将employeeDTO中的所有属性值拷贝到employee中

        //如果用户输入的信息都是合法的,将传入进来的员工对象信息补全
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));//设置默认密码
        employee.setStatus(StatusConstant.ENABLE);//设置默认启用状态

        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        /*//获取登录用户id
        String jwt = request.getHeader("token");//从请求头中获取jwt令牌
        Claims claims = JwtUtil.parseJWT("itcast", jwt);//解析jwt令牌
        Long id = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());*/
        //从当前线程的存储空间中获取当前登录用户的id
        //Long id = BaseContext.getCurrentId();
        //employee.setCreateUser(id);
        //employee.setUpdateUser(id);
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageList(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用分页插件进行分页查询,使用这个插件在编写sql时就不需要添加limit条件了
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //调用mapper接口进行数据层数据查询
        Page<Employee> page = employeeMapper.pageList(employeePageQueryDTO);
        //封装result返回
        return new PageResult(page.getTotal(),page.getResult());
    }
    /**
     * 员工账号的启用或禁用
     * @param id
     * @param status
     */
    @Override
    public void status(Long id, Integer status) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();
        //调用业务层对员工账号状态数据进行修改
//        employeeMapper.status(employee);
        employeeMapper.update(employee);
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();//创建实体类对象给持久层使用
        //调用spring中的bean工具类进行属性值的拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //employee.setUpdateTime(LocalDateTime.now());//修改最后编辑时间为当前
        //employee.setUpdateUser(BaseContext.getCurrentId());//修改编辑人为当前登录员工
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        employee.setPassword("****");//密码传递给前端的时候,隐藏密码
        return employee;
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        Long id = passwordEditDTO.getEmpId();
        Employee employee = employeeMapper.findById(id);//查询当前员工数据
        String oldPassword = employee.getPassword();

        String importOldPassword = passwordEditDTO.getOldPassword();
        importOldPassword = DigestUtils.md5DigestAsHex(importOldPassword.getBytes());
        //判断原密码输入是否正确
        if (!oldPassword.equals(importOldPassword)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //原密码正确,修改
        String password = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        Employee emp = Employee.builder()
                .id(id)
                .password(password)
                .build();
        employeeMapper.update(emp);
    }

}
























